﻿using log4net.Core;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NewsEntity.Models;
using NewsSevicer.Interface;
using NewsSevicer.ResultClass;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace NewsWebsite.Controllers
{
    public class adminController : Controller
    {
        private IAdminServer _adminServer;
        public adminController(IAdminServer adminServer) 
        {

            _adminServer = adminServer;
        
        }
        public IActionResult Index()
        {
           var token= Request.Cookies[".AspNetCore.Cookies"];   
            //如果HttpContext.User.Identity.IsAuthenticated判断token是否过期，没有过期为true，
          //或者HttpContext.User.Claims.Count()大于0表示用户已经登录
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                //这里通过 HttpContext.User.Claims 可以将我们在Login这个Action中存储到cookie中的所有
                //claims键值对都读出来，比如我们刚才定义的UserName的值Wangdacui就在这里读取出来了
                var userName = HttpContext.User.Claims.First().Value;
                return View();
            }
            return Redirect("admin/NewsLogin");
        
  
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
          [HttpPost]
        public ResultData DelectComment([FromBody] CommentModel commentModel)
        {

            try
            {
                if (_adminServer.DelectComment(commentModel.NewsCommentId))
                {
                    return new ResultData { code = 200, message = "删除成功" };
                }

                return new ResultData { code = 500, message = "删除失败服务器异常" };

            }
            catch (Exception)
            {

                return new ResultData { code = 500, message = "删除失败服务器异常" };
            }
        
        
        
        
        }
        /// <summary>
        /// 新闻评论显示
        /// </summary>
        /// <returns></returns>
        public ResultData GetCommentModel()
        {
            try
            {

                ResultData resultData = _adminServer.ResultCommentModel();
                return resultData;
            }
            catch (Exception)
            {

                return new ResultData { code = 500, message = "失败了" };
            }
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        public int add() {
            return 1 + 2;
        
        
        }


        public IActionResult Banner()
        {


            return View();
        }

     

        public IActionResult NewsEdit() {

            var queryParams = HttpContext.Request.Query;
            if (queryParams.ContainsKey("param1"))
            {
                var value1 = queryParams["param1"];
                // 将参数值设置给 <h1> 元素
                ViewData["NewsTitle"] = value1;
            }
            if (queryParams.ContainsKey("param2"))
            {
                var value2 = queryParams["param2"];
                ViewData["NewsId"] = value2;
                // 进一步处理
                //获取当前网站端口拼接给图片
                string url = GetCompleteUrl();
             
               List<string> imglist = _adminServer.GetNewsimages(Convert.ToInt32(value2.ToString()));
                for (int i = 0; i < imglist.Count; i++)
                {
                    imglist[i] = url+imglist[i];
                }
                ViewData["ImagesList"] = imglist;
            }

           

            return View();
        }

        [HttpGet]
        public List<string> GetNewsImages(int Id) 
        {
            //获取当前网站端口拼接给图片
            string url = GetCompleteUrl();
            List<string> imglist = _adminServer.GetNewsimages(Id);
            for (int i = 0; i < imglist.Count; i++)
            {
                imglist[i] = url + imglist[i];
            }
            return imglist;

        }

        // ASP.NET Core 示例
        [HttpGet]
        public IActionResult GetNewsImagesStr(int id)
        {
            //获取当前网站端口拼接给图片
            string url = GetCompleteUrl();
            List<string> imglist = _adminServer.GetNewsimages(id);
            for (int i = 0; i < imglist.Count; i++)
            {
                imglist[i] = url + imglist[i];
            }
            string result = string.Join(",", imglist);

            // 返回统一格式的JSON
            return Ok(new
            {
                success = !string.IsNullOrEmpty(result),
                data = result ?? ""
            });
        }


        [HttpPost]
        public IActionResult updateNewsContent(string newsId, string editorText) {

            if (string.IsNullOrEmpty(newsId))
            {
                return BadRequest("新闻序号不能为空");
            }

            if (string.IsNullOrEmpty(editorText))
            {
                return BadRequest("编辑器内容不能为空");
            }

            int id;
            if (!int.TryParse(newsId, out id))
            {
                return BadRequest("新闻序号格式不正确");
            }
            //NewsStatus发布状态
            News news = new News { Id = id, NewsContent = editorText  ,NewsStatus=1};
            var result = _adminServer.EditNewsContent(news);
            if (result)
            {
                return Ok();
            }
            return NotFound();


        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultData  GetBannerInfo() {
          string  url  =   GetCompleteUrl();
       var  bannerManager =  _adminServer.GetBannerInfo(url);
            
            return new ResultData {
            code=200,
            message="请求成功",
            data=bannerManager
            
            };
        }

        public IActionResult News() 
        {

           return View();
        }

        [HttpPost]
        public int DelectBanner([FromBody] BannerManager bannerManager) 
        {
            if (_adminServer.DelectBanner(bannerManager))
            {
                return 1;
            }
            return 2;
        
        }
        /// <summary>
        /// 获取编辑的新闻
        /// </summary>
        /// <param name="news"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData GetEditNews([FromBody]News news) 
        {
           ResultData resultData  =     _adminServer.GetEditNews(news.Id, GetCompleteUrl());
         
            return resultData;

        }


        [HttpPost]
        public IActionResult DelectNewsImages([FromBody] News news)
        {
             
    
            if (_adminServer.EditNewsImages(news))
            {
                return Ok();

            }
            ActionResult result = NotFound("删除失败，服务器异常");
            return result;
        }


        [HttpPost]
        public bool EditNews([FromBody]News news) 
        {
            if (_adminServer.EditNews(news))
            {
                return true;

            }
            return false;

        
        
        }




        /// <summary>
        /// 新闻添加 加上[FromBody]才能接收post请求
        /// </summary>
        /// <param name="news">新闻信息</param>
        /// <returns></returns>
        [HttpPost]
        public ResultData AddNews([FromBody] News data) {

            if (data.Image !="" ||data.NewsContent!=""||data.NewsTitle!="")
            {


                data.PublishDate = DateTime.Now;
                data.NewsStatus = 0;//无内容状态
                ResultData resultDatas = _adminServer.AddNews(data);


                return resultDatas;
            }




            return new ResultData {code=500,message="新闻信息不全",data=null };


        }
        public IActionResult articleImagesManages()
        {

            return View();

        }
        public IActionResult NewsLogin() 
        {

            return View();

        }
        [HttpPost]
        public ResultData login([FromBody] Adminlogin adminlogin ) 
        {
            if (_adminServer.AdminLogin(adminlogin))
            {
                var claims = new[] { new Claim("UserName", adminlogin.UserName) };
                var claimsIdentity = new ClaimsIdentity(
             claims,
             CookieAuthenticationDefaults.AuthenticationScheme
            );
                ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity);
                Task.Run(async () =>
                {
                    //登录用户，相当于ASP.NET中的FormsAuthentication.SetAuthCookie
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

                    //可以使用HttpContext.SignInAsync方法的重载来定义持久化cookie存储用户认证信息，例如下面的代码就定义了用户登录后60分钟内cookie都会保留在客户端计算机硬盘上，
                    //即便用户关闭了浏览器，60分钟内再次访问站点仍然是处于登录状态，除非调用Logout方法注销登录。
                    //注意其中的AllowRefresh属性，如果AllowRefresh为true，表示如果用户登录后在超过50%的ExpiresUtc时间间隔内又访问了站点，就延长用户的登录时间（其实就是延长cookie在客户端计算机硬盘上的保留时间），
                    //例如本例中我们下面设置了ExpiresUtc属性为60分钟后，那么当用户登录后在大于30分钟且小于60分钟内访问了站点，那么就将用户登录状态再延长到当前时间后的60分钟。但是用户在登录后的30分钟内访问站点是不会延长登录时间的，
                    //因为ASP.NET Core有个硬性要求，是用户在超过50%的ExpiresUtc时间间隔内又访问了站点，才延长用户的登录时间。
                    //如果AllowRefresh为false，表示用户登录后60分钟内不管有没有访问站点，只要60分钟到了，立马就处于非登录状态（不延长cookie在客户端计算机硬盘上的保留时间，60分钟到了客户端计算机就自动删除cookie）
                    /*
                    await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    user, new AuthenticationProperties()
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
                        AllowRefresh = true
                    });
                    */

                }).Wait();
                return new ResultData { code = 200, message = "登录成功", data = null };
            }

            return new ResultData { code = 500, message = "登录失败", data = null };
        
        }

        /// <summary>
        /// 退出登录 删除cookei
        /// </summary>
        /// <returns></returns>
        public ResultData LoginOut()
        {


            //task启动多线程
            Task.Run(async () => {

                await HttpContext.SignOutAsync();
            }).Wait();



            return new ResultData { code = 200, message = "删除", data = true };

        }


        /// <summary>
        /// //获取当前项目的地址
        /// </summary>
        /// <returns></returns>
        private string GetCompleteUrl()
        {
            
            return new StringBuilder()
                 .Append(HttpContext.Request.Scheme)
                 .Append("://")
                 .Append(HttpContext.Request.Host)
                 .Append(HttpContext.Request.PathBase)
                 //.Append(HttpContext.Request.Path)
                 //.Append(HttpContext.Request.QueryString)
                 .ToString();
        }

        /// <summary>
        /// 添加banner成功
        /// </summary>
        /// <param name="bannerManager"></param>
        /// <returns></returns>

        public int AddBanner([FromBody]BannerManager bannerManager) 
        {
            bannerManager.AddTime = DateTime.Now;

            

            if (_adminServer.AddBanner(bannerManager))
            {
                return 1;

            }
            return 2;
        
        }


        ///// <summary>
        ///// 上传图片
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //public OkObjectResult FileSave(List<IFormFile> files)
        //{

        //    if (files.Count < 1)
        //    {
        //        return Ok("空文件");
        //    }
        //    //返回的文件地址
        //    List<string> filenames = new List<string>();
        //    DateTime now = DateTime.Now;
        //    //文件存储路径
        //    string filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
        //    //获取当前web目录
        //    var webRootPath = "wwwroot/"; ;
        //    if (!Directory.Exists(webRootPath + filePath))
        //    {
        //        Directory.CreateDirectory(webRootPath + filePath);
        //    }
        //    try
        //    {
        //        foreach (var item in files)
        //        {
        //            if (item != null)
        //            {
        //                #region  图片文件的条件判断
        //                //文件后缀
        //                string fileExtension = Path.GetExtension(item.FileName);

        //                //判断后缀是否是图片
        //                const string fileFilt = ".gif|.jpg|.jpeg|.png";
        //                if (fileExtension == null)
        //                {
        //                    break;
        //                    //return Error("上传的文件没有后缀");
        //                }
        //                if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
        //                {
        //                    break;
        //                    //return Error("请上传jpg、png、gif格式的图片");
        //                }

        //                //判断文件大小
        //                long length = item.Length;
        //                if (length > 1024 * 1024 * 2) //2M
        //                {
        //                    break;
        //                    //return Error("上传的文件不能大于2M");
        //                }

        //                #endregion

        //                string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
        //                string strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
        //                string saveName = strDateTime + strRan + fileExtension;

        //                //插入图片数据
        //                using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
        //                {
        //                    item.CopyTo(fs);
        //                    fs.Flush();
        //                }


        //                filenames.Add(filePath + saveName);
        //            }
        //        }
        //        return Ok(filenames);
        //    }
        //    catch (Exception )
        //    {
        //        //这边增加日志，记录错误的原因
        //        //ex.ToString();
        //        return Ok("上传失败");
        //    }
        //}
        /// <summary>
        /// Upload Images
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public OkObjectResult FileSave(List<IFormFile> files)
        {
            if (files == null || files.Count < 1)
            {
                return Ok("No files uploaded");
            }

            // Return list of file paths
            List<string> filenames = new List<string>();
            DateTime now = DateTime.Now;
            // File storage path
            string filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            // Get current web directory
            var webRootPath = "wwwroot/";
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }

            try
            {
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        #region  Image file condition checks
                        // File extension
                        string fileExtension = Path.GetExtension(item.FileName);

                        // Check if the extension is an image
                        const string fileFilt = ".gif|.jpg|.jpeg|.png";
                        if (fileExtension == null)
                        {
                            break;
                        }
                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            break;
                        }

                        // Check file size
                        long length = item.Length;
                        if (length > 1024 * 1024 * 2) // 2MB
                        {
                            break;
                        }

                        #endregion

                        string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); // Get time string
                        string strRan = new Random().Next(100, 999).ToString(); // Generate three-digit random number
                        string saveName = strDateTime + strRan + fileExtension;

                        // Save image data
                        using (FileStream fs = new FileStream(Path.Combine(webRootPath + filePath, saveName), FileMode.Create))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }

                        filenames.Add(filePath + saveName);
                    }
                }
                return Ok(filenames);
            }
            catch (Exception ex)
            {
                // Add logging to record the reason for the error
                // ex.ToString();
                return Ok("Upload failed");
            }
        }


        /// <summary>
        /// banner新闻添加
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public OkObjectResult BannerFileSave(List<IFormFile> files)
        {

            if (files.Count < 1)
            {
                return Ok("空文件");
            }
            //返回的文件地址
            List<string> filenames = new List<string>();
            DateTime now = DateTime.Now;
            //文件存储路径
            string filePath = string.Format("/BannerUploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            //获取当前web目录
            var webRootPath = "wwwroot/"; ;
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        #region  图片文件的条件判断
                        //文件后缀
                        string fileExtension = Path.GetExtension(item.FileName);

                        //判断后缀是否是图片
                        const string fileFilt = ".gif|.jpg|.jpeg|.png";
                        if (fileExtension == null)
                        {
                            break;
                            //return Error("上传的文件没有后缀");
                        }
                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            break;
                            //return Error("请上传jpg、png、gif格式的图片");
                        }

                        //判断文件大小
                        long length = item.Length;
                        if (length > 1024 * 1024 * 2) //2M
                        {
                            break;
                            //return Error("上传的文件不能大于2M");
                        }

                        #endregion

                        string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        string strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        string saveName = strDateTime + strRan + fileExtension;

                        //插入图片数据
                        using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }


                        filenames.Add(filePath + saveName);
                    }
                }
                return Ok(filenames);
            }
            catch (Exception )
            {
                //这边增加日志，记录错误的原因
                //ex.ToString();
                return Ok("上传失败");
            }
        }







        /// <summary>
        /// 添加新闻类别
        /// </summary>
        /// <param name="newsType"></param>
        /// <returns></returns>
        public IActionResult AdminAddNewsType(NewsType newsType) 
        {
                     ResultData result  = _adminServer.AdminAddNewsType(newsType);
            if (result.code==200)
            {
                return Ok(1);
            }
            return Content("出错了！");

        }
        /// <summary>
        /// 获取新闻类别数据
        /// </summary>
        /// <returns></returns>
        public ResultData GetNewsType() 
        {
            try
            {
                ResultData resultData = _adminServer.GetNewsType();

                return resultData;
            }
            catch (Exception )
            {

                throw;
            }
        }

        /// <summary>
        /// 删除新闻类别
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
  
 
        public ResultData  DeleteNewType(int typeid) 
        {
            List<News> list = _adminServer.GetTypeNews(typeid);
            if (list.Count < 1)
            {
                ResultData resultData = _adminServer.DeleteNewsType(typeid);
                if (resultData.code == 200)
                {

                    return new ResultData
                    {
                        code = 200,
                        message = "删除成功",
                        data = null,
                    };
                }
            }
            return new ResultData
            {
                code = 500,
                message = "请删除该分类下所有新闻再删除该类别",
                data = null,

            };



        }
        



        public IActionResult newsclassify() 
        {

            return View();
        }
        public IActionResult comment() {

           return View();
        }
        /// <summary>
        /// 新闻数据
        /// </summary>
        /// <returns></returns>
        public ResultData GetAdminNews()
        {
           object List = _adminServer.GetAdminNews();
            return new ResultData
            {
                code = 200,
                message = "获取成功",
                data = List
            };
        }


     

        /// <summary>
        /// 删除一条新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
       [HttpPost]
        public ResultData DelNews([FromBody]News news)
        {
            try
            {
                int i = _adminServer.DelNews(news);
                if (i == 1)
                {
                    return new ResultData
                    {
                        code = 200,
                        message = "删除成功",
                        data = null
                    };
                }
                else
                {
                    return new ResultData
                    {
                        code = 500,
                        message = "失败",
                        data = null
                    };
                }
            }catch(Exception ex)
            {
                return new ResultData
                {
                    code = 501,
                    message = ex.Message,
                    data = null
                };
            }
        }



        /// <summary>
        /// 真删除一条新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData DelectNews([FromBody] News news)
        {
            try
            {
                int i = _adminServer.DelectNews(news);
                if (i == 1)
                {
                    return new ResultData
                    {
                        code = 200,
                        message = "删除成功",
                        data = null
                    };
                }
                else
                {
                    return new ResultData
                    {
                        code = 500,
                        message = "失败",
                        data = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new ResultData
                {
                    code = 501,
                    message = ex.Message,
                    data = null
                };
            }
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultPaging NewsPaging([FromBody]Paging paging) {
                   ResultPaging  result =     _adminServer.NewsPaging(paging.pageindex, paging.pageSize);

            var WebsiteIP = GetCompleteUrl();
            result.WebsiteIP=WebsiteIP;
            return result;
        }

  


    }
}
